﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using RestSharp;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.Text.RegularExpressions;
using System.Web.UI.WebControls;
using System.Windows.Forms;
using System.Xml.Serialization;
using TmU220PrintHelperV2d0.Entity;
using TmU220PrintHelperV2d0.HttpHelper;
using TmU220PrintHelperV2d0.Singleton;
using ZhangLogSysV1d0;

namespace TmU220PrintHelperV2d0.Service
{
    /// <summary>
    /// 各种不易分类的静态方法集合
    /// </summary>
    public class HotchPotchV2d0
    {
        /// <summary>
        /// 根据当前年月日，得到打印日志文件的文件名
        /// </summary>
        /// <returns></returns>
        public static string GetPrintLogXmlFilename(DateTime printDateTime)
        {
            string basePath = AppDomain.CurrentDomain.BaseDirectory + "\\Logs\\";
            if (!Directory.Exists(basePath))
                Directory.CreateDirectory(basePath);
            string xmlFilename = basePath +
                string.Format("PrintCompleteLog-{0}.xml", printDateTime.ToString("yyyyMMdd"));
            return xmlFilename;
        }

        /// <summary>
        /// 将数据类保存为xml文件
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="printtTempletInfoSet"></param>
        /// <param name="fileName"></param>
        public static void SaveToXmFile<T>(T printtTempletInfoSet, string fileName)
        {
            StreamWriter sW=null;
            try
            {
                XmlSerializer xSerializer = new XmlSerializer(typeof(T));
                sW = new StreamWriter(fileName);            
                xSerializer.Serialize(sW, printtTempletInfoSet);
            }
            catch(Exception ex)
            {
                SimpleLoger.Instance.Error(ex);
            }
            finally
            {
                sW.Close();
            }
        }
        /// <summary>
        /// 读取xml文件,生成对应的数据类
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="fileName"></param>
        /// <returns></returns>
        public static T ReadFromXmlFile<T>(string fileName)
        {
            T result = default(T);
            try
            {
                if (File.Exists(fileName))
                {
                    StreamReader sR = new StreamReader(fileName);
                    XmlSerializer xSerializer = new XmlSerializer(typeof(T));
                    result = (T)xSerializer.Deserialize(sR);
                    sR.Close();
                }
            }
            catch (Exception ex)
            {
                SimpleLoger.Instance.Error(ex);
            }
            return result;
        }

        /// <summary>
        /// 更加打印任务，得到打印记录日志字符串
        /// </summary>
        /// <param name="printTask"></param>
        /// <returns></returns>
        public static string GetPrintRecordLogStr(PrintTaskV2d0 printTask)
        {
            string logString = string.Empty;
            logString = string.Format("管理员:{0}  打印机:{1}  台号:{2}  打印序号:{3}  打印行数:{4}",
                printTask.DataOfPrintTask.adduser, 
                printTask.DataOfPrintTask.act_printer, 
                printTask.DataOfPrintTask.tableno,
                printTask.DataOfPrintTask.print_no,
                printTask.PrintTaskItemList.Count.ToString()
                );
            return logString;
        }
        
        /// <summary>
        /// 深度复制，利用序列化和反序列化的方法
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="RealObject"></param>
        /// <returns></returns>
        public static T Clone<T>(T RealObject)
        {
            using (Stream objectStream = new MemoryStream())
            {
                //利用 System.Runtime.Serialization序列化与反序列化完成引用对象的复制 
                IFormatter formatter = new BinaryFormatter();
                formatter.Serialize(objectStream, RealObject);
                objectStream.Seek(0, SeekOrigin.Begin);
                return (T)formatter.Deserialize(objectStream);
            }
        }
        /// <summary>
        /// 得到由分隔符::连接的字符串的index部分(从0开始）
        /// </summary>
        /// <param name="sourceString"></param>
        /// <param name="separatorSign">分割符</param>
        /// <returns></returns>
        public static string GetSplitPartByIndex(string toBeSplitString, int index, string separatorSign = "::")
        {
            string result = null;
            try
            {
                if(!string.IsNullOrEmpty(toBeSplitString))
                {
                    string[] sArray = Regex.Split(toBeSplitString, separatorSign, RegexOptions.IgnoreCase);
                    if (sArray.Count() > index) result = sArray[index];
                    else result = string.Empty;
                }
            }
            catch (Exception ex)
            {
                SimpleLoger.Instance.Error(ex);
            }
            return result;
        }
        /// <summary>
        /// 加密字符串
        /// 加密 abc1234，结果为6468633a373434
        /// "6468633A373434"
        /// </summary>
        /// <param name="sourceString"></param>
        /// <returns></returns>
        public static string EncryptString(string sourceString)
        {
            string resultString = string.Empty;
            if (string.IsNullOrEmpty(sourceString))
            {
                return string.Empty;
            }
            string ke = "36095106549644D4FB0A0B0246BD0F880BEA088";
            string cs = sourceString;
            int stringLenth = cs.Length - ke.Length;
            if (stringLenth > 0)
            {
                ke = ke.PadRight(cs.Length, 'P');
            }
            string ct = string.Empty;
            StringBuilder ctSBuilder = new StringBuilder();
            for (int i = 0; i < cs.Length; i++)
            {
                string ch = cs.Substring(i, 1);
                string ky = ke.Substring(i, 1);
                int chn = (int)(ch[0]) + (int)(ky[0]) - 48;

                ctSBuilder.Append(chn.ToString("X2"));
            }
            resultString = ctSBuilder.ToString();
            return resultString;
        }


        public static byte[] stringToByteArray(string hexString)
        {
            hexString = hexString.Replace(" ", "");
            if ((hexString.Length % 2) != 0)
                hexString += " ";
            byte[] returnBytes = new byte[hexString.Length / 2];
            for (int i = 0; i < returnBytes.Length; i++)
                returnBytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 16);
            return returnBytes;
        }
        /// <summary>
        /// 解密字符串
        /// </summary>
        /// <param name="sourceString"></param>
        /// <returns></returns>
        public static string DecryptString(string sourceString)
        {
            string resultString = string.Empty;
            if (string.IsNullOrEmpty(sourceString))
            {
                return string.Empty;
            }
            string ke = "36095106549644D4FB0A0B0246BD0F880BEA088";
            byte[] byteArray = stringToByteArray(sourceString);
            StringBuilder tmpSB = new StringBuilder();
            foreach (byte item in byteArray)
            {
                tmpSB.Append((char)item);
            }
            string cs = tmpSB.ToString();
            int len = cs.Length - ke.Length;
            if (len > 0)
            {
                ke = ke.PadRight(cs.Length, 'P');
            }
            string ct = string.Empty;
            StringBuilder ctSBuilder = new StringBuilder();
            for (int i = 0; i < cs.Length; i++)
            {
                string ch = cs.Substring(i, 1);
                string ky = ke.Substring(i, 1);
                int chn = (int)(ch[0]) - (int)(ky[0]) + 48;
                ctSBuilder.Append((char)chn);
            }
            resultString = ctSBuilder.ToString();
            return resultString;
        }
        /// <summary>
        /// 得到api接口GetTableData的post数据
        /// </summary>
        /// <param name="tableName"></param>
        /// <param name="timeStamp"></param>
        /// <param name="url"></param>
        /// <returns></returns>
        public static string GetPostDataOfGetTableData(string tableName,string timeStamp= "20190212090102", string url = "http://api.legendleader.com/index.php/api/rms/")
        {
            string cParam =string.Format("tablename={0}",tableName);
            string method = "common.getTableData";
            string encryptSign = HotchPotchV2d0.EncryptString(method + timeStamp);
            string postData = cParam + "&method=" + method + "&sign=" + encryptSign + "&timestamp="+timeStamp;
            return postData;
        }


        /// <summary>
        /// 得到api接口GetTableData的post数据
        /// </summary>
        /// <param name="tableName"></param>
        /// <param name="timeStamp"></param>
        /// <param name="url"></param>
        /// <returns></returns>
        public static string GetPostDataOfGetTableDataByParam(string tableName, string key,string value,string timeStamp = "20190212090102", string url = "http://api.legendleader.com/index.php/api/rms/")
        {
            string cParam = string.Format("tablename={0}&key={1}&value={2}", tableName,key,value);
            string method = "common.getTableDataByParam";
            string encryptSign = HotchPotchV2d0.EncryptString(method + timeStamp);
            string postData = cParam + "&method=" + method + "&sign=" + encryptSign + "&timestamp=" + timeStamp;
            return postData;
        }
        public static string GetPostDataOfGetDataBySQL(string sqlString, string timeStamp = "20190212090102", string url = "http://api.legendleader.com/index.php/api/rms/")
        {
            string cParam = string.Format("SQL={0}",sqlString);
            string method = "common.getDataBySQL";
            string encryptSign = HotchPotchV2d0.EncryptString(method + timeStamp);
            string postData = cParam + "&method=" + method + "&sign=" + encryptSign + "&timestamp=" + timeStamp;
            return postData;
        }
        public static string GetPostDataOfUpdateTableData(string tableName,string key,string value,string jsonData, string timeStamp = "20190212090102", string url = "http://api.legendleader.com/index.php/api/rms/")
        {
            string cParam = string.Format("tablename={0}&key={1}&value={2}&data={3}", tableName,key,value,jsonData);
            string method = "common.updateTableData";
            string encryptSign = HotchPotchV2d0.EncryptString(method + timeStamp);
            string postData = cParam + "&method=" + method + "&sign=" + encryptSign + "&timestamp=" + timeStamp;
            return postData;
        }

        /// <summary>
        /// 设置对象的某个属性的值
        /// </summary>
        /// <param name="propertyName"></param>
        /// <param name="value"></param>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static bool SetObjectPropertyValue(string propertyName, string value, object obj)
        {
            try
            {
                Type objectType = obj.GetType();
                PropertyInfo pInfo = objectType.GetProperty(propertyName);
                if(pInfo!=null)
                {
                    object v = Convert.ChangeType(value, pInfo.PropertyType);
                    pInfo.SetValue(obj, v, null);
                    return true;
                }
                return false;
            }
            catch
            {
                return false;
            }
        }
        /// <summary>
        /// 得到对象某个属性的值 日期时间属性所特别处理，只保留时分秒
        /// </summary>
        /// <param name="propertyName"></param>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static string GetObjectPropertyStringValue(string stringIncludePropertyName, object obj)
        {
            string result = null;
            try
            {
                Type objectType = obj.GetType();
                PropertyInfo pInfo = objectType.GetProperty(stringIncludePropertyName);
                if (pInfo != null)
                {
                    object currObject = pInfo.GetValue(obj, null);
                    Type pType = currObject.GetType();
                    // 日期时间，只保留时分秒
                    if(pType==typeof(DateTime))
                    {
                        var temp = (DateTime)currObject;
                        result = temp.ToString("yyyy/MM/dd HH:mm");
                        //result = temp.ToString();
                        //return Value;
                    }
                    else
                    {
                        //string Value = Convert.ToString(currObject);
                        result= Convert.ToString(currObject);
                        //return Value;
                    }                     
                }
                //else return null;
            }
            catch (Exception ex)
            {
                SimpleLoger.Instance.Error(ex);
            }
            return result;
        }
        public static object GetObjectProperty(string propertyName, object obj)
        {
            try
            {
                Type objectType = obj.GetType();
                PropertyInfo pInfo = objectType.GetProperty(propertyName);
                if (pInfo != null)
                {
                    object o = pInfo.GetValue(obj, null);
                    return o;
                }
                else return null;
            }
            catch
            {
                return null;
            }
        }
        /// <summary>
        /// 解析带大括号的字符串
        /// </summary>
        /// <param name="content"></param>
        /// <param name="frontString"></param>
        /// <param name="middleString"></param>
        /// <param name="backString"></param>
        public static void ParseBraceString(string content,out string frontString,out string middleString,out string backString)
        {
            frontString = "";
            middleString = "";
            backString = "";
            int startIndex = content.IndexOf('{');
            if(startIndex>=0) frontString = content.Substring(0, startIndex);
            int endIndex = content.IndexOf('}');
            if(endIndex>=0) backString = content.Substring(endIndex + 1);
            if (startIndex >= 0 && endIndex >= 0) middleString = content.Substring(startIndex + 1, endIndex - startIndex-1);
            else frontString = content;
        }
        /// <summary>
        /// 根据类名，得到类的实例
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="classNameOfT"></param>
        /// <returns></returns>
        public static T GetInstance<T>(string classNameOfT)
        {
            return (T)Assembly.Load(Assembly.GetAssembly(typeof(T)).GetName().Name).CreateInstance(typeof(T).Namespace + "." + classNameOfT);
        }
        /// <summary>
        /// 使用api接口读取与T对应的数据表的所有记录，使用common.getTableData接口
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public static List<T> LoadWholeDataOfTableByApiInterface<T>()
        {
            List<T> resultList = null;
            try
            {
                //得到项目主Url
                string url = ApiInterfaceInfoSingletonV3d0.Instance.GetProjectMainUrl();
                //根据类，得到类名称，类名称默认就是对应数据表的表名称
                Type currType = typeof(T);
                string currClassName = currType.Name;
                //表名称
                string tableName = currClassName;
                string timeStamp = "20190216010000";
                //构建post数据
                string postData = HotchPotchV2d0.GetPostDataOfGetTableData(tableName, timeStamp, url);
                //同步方式调用接口
                string returnString = HttpFunctionV2d0.RunApiInterfacePost(url, postData);
            
                if (!string.IsNullOrEmpty(returnString))
                {
                    //解析接口返回json串
                    dynamic rootDynamicObject = JsonConvert.DeserializeObject<dynamic>(returnString);
                    dynamic statusDynamicObject = rootDynamicObject.status;
                    if (rootDynamicObject.status.Value.ToString() == "00")
                    {
                        string contentString = rootDynamicObject.content.ToString();
                        resultList = JsonConvert.DeserializeObject<List<T>>(contentString);
                    }
                }
            }
            catch (Exception ex)
            {
                SimpleLoger.Instance.Error(ex);
            }

            return resultList;
        }
        public static List<T> LoadTableByApiInterface<T>()
        {
            List<T> resultList = null;
            try
            {
                //得到项目主Url
                string url = ApiInterfaceInfoSingletonV3d0.Instance.GetProjectMainUrl();
                //根据类，得到类名称，类名称默认就是对应数据表的表名称
                Type currType = typeof(T);
                string currClassName = currType.Name;
                //表名称
                string tableName = currClassName;
                string timeStamp = "20190216010000";
                //构建post数据
                string postData = HotchPotchV2d0.GetPostDataOfGetTableData(tableName, timeStamp, url);

                string contentType = "application/x-www-form-urlencoded;charset=utf-8"; //Content-Type
                var client = new RestClient(url);
                var request = new RestRequest(Method.POST);
                request.Timeout = 5000;
                request.RequestFormat = DataFormat.Json;
                request.AddParameter(contentType, postData, ParameterType.RequestBody);
                IRestResponse response = client.Execute(request);

                string returnString=response.Content; //返回的结果
                if (!string.IsNullOrEmpty(returnString))
                {
                    //解析接口返回json串
                    dynamic rootDynamicObject = JsonConvert.DeserializeObject<dynamic>(returnString);
                    dynamic statusDynamicObject = rootDynamicObject.status;
                    if (rootDynamicObject.status.Value.ToString() == "00")
                    {
                        string contentString = rootDynamicObject.content.ToString();
                        resultList = JsonConvert.DeserializeObject<List<T>>(contentString);
                    }
                }
            }
            catch (Exception ex)
            {
                SimpleLoger.Instance.Error(ex);
            }

            return resultList;
        }
        public static List<T> GetDataBySQLWithApi<T>()
        {
            List<T> resultList = null;
            try
            {
                // 得到项目主Url
                // 'http://api.legendleader.com/index.php'
                string url = "http://api.legendleader.com/index.php/api/getdatabysql";
                //根据类，得到类名称，类名称默认就是对应数据表的表名称
                Type currType = typeof(T);
                string currClassName = currType.Name;
                //表名称 内部约定，类名称就是表名称
                string tableName = currClassName;
                //string timeStamp = "20190216010000";
                //构建post数据

                // string sqlString = "sql=select * from rms_printer";
                string sqlString = string.Format("sql=select * from {0}", tableName);
                //var jsonObject = new JObject {{ "sql", sqlString }};
                //string jsonString = JsonConvert.SerializeObject(jsonObject);
                //string postData = jsonString;

                string contentType = "application/x-www-form-urlencoded;charset=utf-8"; //Content-Type
                var client = new RestClient(url);
                var request = new RestRequest(Method.POST);
                request.Timeout = 8000;
                request.AddParameter(contentType, sqlString, ParameterType.RequestBody);
                IRestResponse response = client.Execute(request);

                string returnString = response.Content; //返回的结果
                if (!string.IsNullOrEmpty(returnString))
                {
                    //解析接口返回json串
                    dynamic rootDynamicObject = JsonConvert.DeserializeObject<dynamic>(returnString);
                    string codeString = rootDynamicObject.code.Value.ToString();
                    if (codeString == "0")
                    {
                        string contentString = rootDynamicObject.data.list.ToString();
                        resultList = JsonConvert.DeserializeObject<List<T>>(contentString);
                    }
                }
            }
            catch (Exception ex)
            {
                SimpleLoger.Instance.Error(ex);
            }
            return resultList;
        }
        /// <summary>
        /// 将json字符串转化为对应的对象数组
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="jsonString"></param>
        /// <returns></returns>
        public static List<T> DeserializeJsonString<T>(string jsonString)
        {
            List<T> resultList = null;
            resultList = JsonConvert.DeserializeObject<List<T>>(jsonString);
            return resultList;
        }
        /// <summary>
        /// 得到指定类对应的数据表的数据，使用webApi
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public static List<T> GetDataBySql_WebApi<T>()
        {
            List<T> resultList = null;
            try
            {
                Type currType = typeof(T);
                string currClassName = currType.Name;
                //表名称 内部约定，类名称就是表名称
                string tableName = currClassName;
                string sqlString = string.Format("sql=select * from {0}", tableName);
                string jsonString = GetStringOfDataBySql_WebApi(sqlString);
                //解析 反序列化
                resultList = DeserializeJsonString<T>(jsonString);
            }
            catch (Exception ex)
            {
                SimpleLoger.Instance.Error(ex);
            }
            return resultList;
        } 
        /// <summary>
        /// 使用web端的api读取数据表数据（不加密的接口）,返回为json串，需要反序列化为对象数组
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public static string GetStringOfDataBySql_WebApi(string sqlString,string apiUrl= "http://api.legendleader.com/index.php/api/getdatabysql")
        {
            string resultString = "";
            try
            {
                if (string.IsNullOrEmpty(sqlString)) return "";               

                string contentType = "application/x-www-form-urlencoded;charset=utf-8"; //Content-Type
                var client = new RestClient(apiUrl);
                var request = new RestRequest(Method.POST);
                request.Timeout = 8000;
                request.AddParameter(contentType, sqlString, ParameterType.RequestBody);
                IRestResponse response = client.Execute(request);
                string returnString = response.Content; //返回的结果
                if (!string.IsNullOrEmpty(returnString))
                {
                    //解析接口返回json串
                    dynamic rootDynamicObject = JsonConvert.DeserializeObject<dynamic>(returnString);
                    string codeString = rootDynamicObject.code.Value.ToString();
                    if (codeString == "0")
                    {
                        string contentString = rootDynamicObject.data.list.ToString();
                        return contentString;
                    }
                }
            }
            catch (Exception ex)
            {
                SimpleLoger.Instance.Error(ex);
            }
            return resultString;

        }
        public static bool Updatetable_WebApi<T>(List<T> dataList,string apiUrl = "http://api.legendleader.com/index.php/userzhang/updatetable_net")
        {
            bool result = false;
            try
            {
                string url = apiUrl;
                //根据类，得到类名称，类名称内部约定就是对应数据表的表名称
                Type classType = typeof(T);
                string className = classType.Name;
                string tableName = className;
                string jsonStringOfData = "";
                var jsonObject = new JObject {{ "uid", "2222" }, { "name3", "testtest" } , {"printername","tttt" }
                                            };
                var jsonObject1 = new JObject {{ "uid", "3333" }, { "name4", "testtest" }, {"printername","yyyy" }
                                            };
                var jsonOjbectlist = new List<JObject>();
                jsonOjbectlist.Add(jsonObject);
                jsonOjbectlist.Add(jsonObject1);
                jsonStringOfData = JsonConvert.SerializeObject(dataList.ToArray());
                //jsonStringOfData= "{ \"F_ModuleId\": \"1\", \"F_ParentId\": \"0\", \"F_EnCode\": \"SysManage\"},{ \"F_ModuleId\": \"1\", \"F_ParentId\": \"0\", \"F_EnCode\": \"SysManage\"}";
                string paramString = string.Format("tablename={0}&data={1}", tableName,jsonStringOfData);
                //application/json
                string contentType = "application/x-www-form-urlencoded;charset=utf-8"; //Content-Type
                var client = new RestClient(url);
                var request = new RestRequest(Method.POST);
                request.Timeout = 8000;
                request.AddParameter(contentType, paramString, ParameterType.RequestBody);
                IRestResponse response = client.Execute(request);
                string returnString = response.Content; //返回的结果
                if (!string.IsNullOrEmpty(returnString))
                {
                    //解析接口返回json串
                    dynamic rootDynamicObject = JsonConvert.DeserializeObject<dynamic>(returnString);
                    string codeString = rootDynamicObject.code.Value.ToString();
                    if (codeString == "0")
                    {
                        result = true;
                    }
                }
            }
            catch (Exception ex)
            {
                SimpleLoger.Instance.Error(ex);
            }
            return result;

        }
        /// <summary>
        /// 读取数据表的符合条件的记录，使用common.getTableDataByParam接口
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public static List<T> LoadSpecialDataOfTableByApiInterface<T>(string key,string value)
        {
            List<T> resultList = new List<T>();
            try
            {
                //得到项目主Url
                string url = ApiInterfaceInfoSingletonV3d0.Instance.GetProjectMainUrl();
                //url = PhpApiSetSingletonV1d0.Instance.GetProjectMainUrl();
                //根据类，得到类名称，类名称默认就是对应数据表的表名称
                Type currType = typeof(T);
                string currClassName = currType.Name;
                //表名称
                string tableName = currClassName;
                string timeStamp = "20190216010000";
                //构建post数据
                string postData = HotchPotchV2d0.GetPostDataOfGetTableDataByParam(tableName, key, value, timeStamp, url);
                //同步方式调用接口
                string returnString = HttpFunctionV2d0.RunApiInterfacePost(url, postData);
                //解析接口返回json串
                dynamic rootDynamicObject = JsonConvert.DeserializeObject<dynamic>(returnString);
                if (rootDynamicObject != null)
                {
                    dynamic statusDynamicObject = rootDynamicObject.status;
                    if (rootDynamicObject.status.Value.ToString() == "00")
                    {
                        string contentString = rootDynamicObject.content.ToString();
                        if (!string.IsNullOrEmpty(contentString))
                        {
                            resultList = JsonConvert.DeserializeObject<List<T>>(contentString);
                        }
                    }
                }
            }
            catch(Exception ex)
            {
                SimpleLoger.Instance.Error(ex);
            }
            return resultList;
        }
        /// <summary>
        /// 使用sql语句查询数据表的记录（目前仅支持单一表查询） T 应与sql语句查询的表对应，且返回所有字段
        /// </summary> 
        /// <typeparam name="T"></typeparam>
        /// <param name="sqlString"></param>
        /// <returns></returns>
        public static List<T> SqlLoadDataOfTableByApiInterface<T>(string sqlString)
        {
            List<T> resultList = null;
            try
            {
                //得到项目主Url
                string url = ApiInterfaceInfoSingletonV3d0.Instance.GetProjectMainUrl();
                //根据类，得到类名称，类名称默认就是对应数据表的表名称
                Type currType = typeof(T);
                string currClassName = currType.Name;
                //表名称
                string timeStamp = "20190216010000";
                //构建post数据
                string postData = HotchPotchV2d0.GetPostDataOfGetDataBySQL(sqlString, timeStamp, url);
                //同步方式调用接口
                string returnString = HttpFunctionV2d0.RunApiInterfacePost(url, postData);
                //解析接口返回json串
                dynamic rootDynamicObject = JsonConvert.DeserializeObject<dynamic>(returnString);
                dynamic statusDynamicObject = rootDynamicObject.status;
                if (rootDynamicObject.status.Value.ToString() == "00")
                {
                    string contentString = rootDynamicObject.content.ToString();
                    resultList = JsonConvert.DeserializeObject<List<T>>(contentString);
                }
            }
            catch (Exception ex)
            {
                SimpleLoger.Instance.Error(ex);
            }
            return resultList;
        }
        public static bool UpdateTableByApiInterface(string tableName,string key,string value,string jsonData)
        {
            bool result = false;
            try
            {
                //得到项目主Url
                string url = ApiInterfaceInfoSingletonV3d0.Instance.GetProjectMainUrl();
                //表名称
                string timeStamp = "20190216010000";
                //构建post数据
                string postData = HotchPotchV2d0.GetPostDataOfUpdateTableData(tableName, key, value, jsonData, timeStamp, url);
                //同步方式调用接口
                string returnString = HttpFunctionV2d0.RunApiInterfacePost(url, postData);
                //解析接口返回json串
                dynamic rootDynamicObject = JsonConvert.DeserializeObject<dynamic>(returnString);
                if (rootDynamicObject != null)
                {
                    dynamic statusDynamicObject = rootDynamicObject.status;
                    if (rootDynamicObject.status.Value.ToString() == "00")
                    {
                        result = true;
                    }
                }
            }
            catch(Exception ex)
            {
                SimpleLoger.Instance.Error(ex);
            }
            return result;
        }
        /// <summary>
        /// 某打印任务打印完成时，更新rms_order_print_main数据表相关字段
        /// </summary>
        /// <param name="printMainId"></param>
        /// <param name="printerName"></param>
        /// <returns></returns>
        public static bool UpdatePrintMainTableWhenTaskPrintComplete(int printMainId,string printerName)
        {
            //将该打印任务对应的数据表记录的status字段设置为1，
            //将printtime字段设置为当前时间
            //将act_printer字段设置为当前打印机
            bool result = false;
            try
            {
                string tableName = "rms_order_print_main";
                var jsonObject = new JObject {{ "status", "1" } ,
                                            { "printtime", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") },
                                            { "act_printer", printerName }
                                        };
                  string jsonString = JsonConvert.SerializeObject(jsonObject);
                result = HotchPotchV2d0.UpdateTableByApiInterface(tableName, "id", printMainId.ToString(), jsonString);
                //result = UpdateDataKeyValueDataNetSingletonV1d0.Instance.Run<rms_order_print_main>("id", printMainId.ToString(), jsonString);
            }
            catch(Exception ex)
            {
                SimpleLoger.Instance.Error(ex);
            }
            return result;
        }
        /// <summary>
        /// 添加打印日志文件到数据表rms_order_print_log
        /// </summary>
        /// <param name="printLog"></param>
        /// <returns></returns>
        public static bool InsertSinglePrintLogToTable(PrintLogV3d0 printLog)
        {
            bool result = false;
            rms_order_print_log print_log = new rms_order_print_log(printLog);
            string resultUid=SetDataNetSingletonV1d0.Instance.Run<rms_order_print_log>(print_log);
            if (Convert.ToInt32(resultUid) > 0) result = true;
            //string tableName = "rms_order_print_log";
            //List<JObject> jsList = new List<JObject>();
            //List<rms_order_print_log> tmpPrintLogList = new List<rms_order_print_log>();
            //tmpPrintLogList.Add(print_log);
            //string jsonListString = JsonConvert.SerializeObject(tmpPrintLogList);
            //result = HotchPotchV2d0.UpdateTableByApiInterface(tableName, "uid", print_log.uid, jsonListString);
            return result;
        }
        /// <summary>
        /// 更新rms_printer表相应status,lastupdatetime字段
        /// </summary>
        /// <param name="status"></param>
        /// <returns></returns>
        public static bool UpdatePrinterTable(int printerId,int status)
        {
            bool result = false;
            try
            {
                string tableName = "rms_printer";
                var jsonObject = new JObject { { "status", status.ToString() } ,
                                            { "lastupdatetime", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") },
                                        };
                string jsonString = JsonConvert.SerializeObject(jsonObject);
                result = HotchPotchV2d0.UpdateTableByApiInterface(tableName, "id", printerId.ToString(), jsonString);
            }
            catch (Exception ex)
            {
                SimpleLoger.Instance.Error(ex);
            }
            return result;
        }
        public static bool InsertPrinterTable()
        {
            bool result = false;
            try
            {
                string tableName = "rms_printer";
                var jsonObject = new JObject { { "id", "_5FP0L50AF" } ,
                                            { "uid", "AABBCC"},
                                            { "name1", "Bar1" },
                                            { "printername", "Bar1" }
                                        };
                result = HotchPotchV2d0.UpdateTableByApiInterface(tableName, "id", "_5FP0L50AF", jsonObject.ToString());
            }
            catch (Exception ex)
            {
                SimpleLoger.Instance.Error(ex);
            }
            return result;
        }
        /// <summary>
        /// 根据画板像素宽度，对字符串进行折行处理（在适当的位置插入换行符）
        /// </summary>
        /// <param name="content"></param>
        /// <param name="fontSize"></param>
        /// <param name="width"></param>
        /// <param name="row"></param>
        /// <returns></returns>
        public static string ContentWarp(string content, int fontSize, float width, out int row,string deviceType="TM-U220")
        {
            content = content.Replace(Environment.NewLine, string.Empty);

            var builder = new StringBuilder();
            float nowWidth = 0;
            row = 1;
            foreach (char item in content)
            {
                string strOfChar = new string(item, 1);
                
                float charWidth = GetCharWidthWithGdi(item, fontSize, deviceType); ;
                nowWidth += charWidth;
                if (nowWidth > width)
                {
                    builder.Append(Environment.NewLine);
                    nowWidth = charWidth;
                    row++;
                }
                builder.Append(item);
            }
            string resultString = builder.ToString();
            return builder.ToString();
        }
        /// <summary>
        /// 得到单个字符的宽度
        /// </summary>
        /// <param name="singleChar"></param>
        /// <param name="fontSize"></param>
        /// <returns></returns>
        public static float GetCharWidth(char singleChar,int fontSize)
        {
            //const float _charProportion = 0.7352f;
            const float _charProportion = 0.91f;// tm-u220B
            int codeOfSingleChar = Convert.ToInt32(singleChar);
            float charWidth = codeOfSingleChar < 128 ? _charProportion * (int)fontSize : _charProportion * (int)fontSize * 2;
            return charWidth;
        }
        /// <summary>
        /// 得到字符的宽度
        /// </summary>
        /// <param name="singleChar"></param>
        /// <param name="fontSize"></param>
        /// <returns></returns>
        public static float GetCharWidthWithGdi(char singleChar, int fontSize,string deviceType="TM-U220")
        {
            //汉字系数
            double hzFontRito =0;
            //asc字符系数
            double ascFontRito =0;
            if(deviceType=="TM-U220")
            {
                hzFontRito = 1.940;
                ascFontRito = 0.875;
            } else if (deviceType == "XP-Q200")
            {
                hzFontRito = 1.600;
                ascFontRito = 0.800;
            } else
            {
                hzFontRito = 1.940;
                ascFontRito = 0.875;
            }
            if (singleChar >= 0x4e00 && singleChar <= 0x9fbb)
            {
                return (float)hzFontRito * fontSize;
            }
            else
            {
                return (float)ascFontRito * fontSize;
            }
        }
        public static SizeF GetStringSizeFWithGdi(string content, int fontSize)
        {
            Font currFont = new Font("Arial", fontSize);
            Bitmap currBmp = new Bitmap(1, 1);
            Graphics currGraphics = Graphics.FromImage(currBmp);
            StringFormat sf = StringFormat.GenericDefault;
            SizeF currSizeF = currGraphics.MeasureString(content, currFont, 0, sf);
            currBmp.Dispose();
            currFont.Dispose();
            return currSizeF;
        }
        public enum FontSize
        {
            micro = 4,
            Small = 6,
            Normal = 10,
            Large = 14,
            Huge = 16
        }
        public enum PaperWidth
        {
            /// <summary>
            /// 80mm
            /// </summary>
            Paper80mm = 80,
            /// <summary>
            /// 76mm
            /// </summary>
            Paper76mm = 76,
            /// <summary>
            /// 58mm
            /// </summary>
            Paper58mm = 58
        }
        public static bool IsIP(string ip)
        {
            //判断是否为IP
            return Regex.IsMatch(ip, @"^((2[0-4]\d|25[0-5]|[01]?\d\d?)\.){3}(2[0-4]\d|25[0-5]|[01]?\d\d?)$");
        }
        public static string ConvertStringToHex(string strASCII, string separator = null)
        {
            StringBuilder sbHex = new StringBuilder();
            foreach (char chr in strASCII)
            {
                sbHex.Append(String.Format("{0:X2}", Convert.ToInt32(chr)));
                sbHex.Append(separator ?? string.Empty);
            }
            return sbHex.ToString();
        }

    }    

}
